<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="formData.name"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入商品名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品分类" prop="categoryId">
      <el-cascader
        v-if="categoryList.length > 0"
        v-model="formData.categoryId"
        :options="categoryList"
        :props="cascaderProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择商品分类"
        :show-all-levels="true"
      />
      <el-alert
        v-else
        title="未找到驾校服务分类，请联系管理员检查分类配置"
        type="warning"
        :closable="false"
        show-icon
      />
    </el-form-item>
    <el-form-item label="商品品牌" prop="brandId">
      <el-select v-model="formData.brandId" class="w-80" placeholder="请选择商品品牌">
        <el-option
          v-for="item in brandList"
          :key="item.id"
          :label="item.name"
          :value="item.id as number"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="商品关键字" prop="keyword">
      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />
    </el-form-item>
    <el-form-item label="商品简介" prop="introduction">
      <el-input
        v-model="formData.introduction"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="128"
        placeholder="请输入商品简介"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品封面图" prop="picUrl">
      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
    </el-form-item>
    <el-form-item label="商品轮播图" prop="sliderPicUrls">
      <UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/carrent'
import * as ProductCategoryApi from '@/api/mall/product/category'
import * as ProductBrandApi from '@/api/mall/product/brand'
import { BrandVO } from '@/api/mall/product/brand'

defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗

const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  brandId: undefined // 商品品牌
})
const rules = reactive({
  name: [required],
  categoryId: [required],
  keyword: [required],
  introduction: [required],
  picUrl: [required],
  sliderPicUrls: [required],
  brandId: [required]
})

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  {
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 初始化 */
const brandList = ref<BrandVO[]>([]) // 商品品牌列表
const categoryList = ref<any[]>([]) // 商品分类树（使用any类型因为handleTree会添加children属性）

// 级联选择器配置
const cascaderProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  emitPath: false, // 只返回选中节点的值，不返回路径数组
  expandTrigger: 'hover' as const, // 鼠标悬停展开子菜单
  checkStrictly: false // 是否严格的遵守父子节点不互相关联
}

// 教练车的父分类ID
const COACH_PARENT_CATEGORY_ID = 87

/**
 * 过滤教练车相关的分类
 * 只显示父分类87及其所有子分类
 */
const filterCoachCategories = (categories: any[]): any[] => {
  console.log('🔍 开始过滤教练车分类，目标父分类ID:', COACH_PARENT_CATEGORY_ID)

  const result: any[] = []

  const findCoachCategories = (cats: any[]) => {
    cats.forEach(category => {
      // 如果是父分类87，包含它及其所有子分类
      if (category.id === COACH_PARENT_CATEGORY_ID) {
        console.log(`✅ 找到目标父分类: [${category.id}] ${category.name}`)
        console.log(`   子分类数量: ${category.children?.length || 0}`)

        // 显示子分类详情
        if (category.children && category.children.length > 0) {
          console.log('   子分类列表:')
          category.children.forEach((child: any) => {
            console.log(`     - [${child.id}] ${child.name}`)
          })
        }

        result.push({
          ...category,
          children: category.children || []
        })
      }
      // 递归检查子分类
      else if (category.children && category.children.length > 0) {
        findCoachCategories(category.children)
      }
    })
  }

  findCoachCategories(categories)

  if (result.length === 0) {
    console.warn('⚠️ 未找到教练车分类，请检查分类ID是否正确')
  } else {
    console.log('✅ 教练车分类过滤完成')
  }

  return result
}

/**
 * 根据ID查找分类
 */
const findCategoryById = (categories: any[], id: number): any => {
  for (const category of categories) {
    if (category.id === id) {
      return category
    }
    if (category.children && category.children.length > 0) {
      const found = findCategoryById(category.children, id)
      if (found) return found
    }
  }
  return null
}

onMounted(async () => {
  console.log('=== 教练车表单初始化开始 ===')

  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  const fullCategoryTree = handleTree(data, 'id', 'parentId')

  // 过滤出教练车相关的分类（父分类87及其子分类）
  categoryList.value = filterCoachCategories(fullCategoryTree)

  // 调试信息：打印原始分类数据和过滤后的数据
  console.log('=== 分类过滤结果 ===')
  console.log('原始分类数量:', fullCategoryTree.length)
  console.log('过滤后的教练车分类数量:', categoryList.value.length)
  console.log('过滤后的分类详情:', categoryList.value.map(cat => ({
    id: cat.id,
    name: cat.name,
    childrenCount: cat.children?.length || 0,
    children: cat.children?.map((child: any) => ({ id: child.id, name: child.name })) || []
  })))
  console.log('=== 分类过滤完成 ===')

  // 打印分类层级结构
  console.log('=== 教练车分类层级结构 ===')
  categoryList.value.forEach(category => {
    console.log(`父分类: [${category.id}] ${category.name}`)
    if (category.children && category.children.length > 0) {
      category.children.forEach(child => {
        console.log(`  └─ 子分类: [${child.id}] ${child.name}`)
        if (child.children && child.children.length > 0) {
          child.children.forEach(grandChild => {
            console.log(`    └─ 孙分类: [${grandChild.id}] ${grandChild.name}`)
          })
        }
      })
    }
  })

  // 获取商品品牌列表
  brandList.value = await ProductBrandApi.getSimpleBrandList()

  // 验证当前商品分类是否在允许的范围内
  if (formData.categoryId) {
    const isValidCategory = validateCategoryInCoachRange(formData.categoryId)
    if (!isValidCategory) {
      console.warn(`⚠️ 当前商品分类 [${formData.categoryId}] 不在驾校服务分类范围内`)
    } else {
      console.log(`✅ 当前商品分类 [${formData.categoryId}] 在驾校服务分类范围内`)
    }
  }

  console.log('=== 教练车表单初始化完成 ===')
})

/**
 * 验证分类ID是否在驾校服务分类范围内
 */
const validateCategoryInCoachRange = (categoryId: number): boolean => {
  const findInCategories = (categories: any[]): boolean => {
    for (const category of categories) {
      if (category.id === categoryId) {
        return true
      }
      if (category.children && category.children.length > 0) {
        if (findInCategories(category.children)) {
          return true
        }
      }
    }
    return false
  }

  return findInCategories(categoryList.value)
}
</script>
